package org.ruoyi.chat.config;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.ruoyi.common.chat.openai.OpenAiStreamClient;
import org.ruoyi.common.chat.openai.function.KeyRandomStrategy;
import org.ruoyi.common.chat.openai.interceptor.OpenAILogger;
import org.ruoyi.common.core.service.ConfigService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Chat配置类
 *
 * @date: 2023/5/16
 */
@Log4j2
@Configuration
@RequiredArgsConstructor
public class ChatConfig {

    @Getter
    private OpenAiStreamClient openAiStreamClient;

    private final ConfigService configService;

    @Bean
    public OpenAiStreamClient openAiStreamClient() {
        String apiHost = configService.getConfigValue("chat", "apiHost");
        String apiKey = configService.getConfigValue("chat", "apiKey");
        openAiStreamClient = createOpenAiStreamClient(apiHost,apiKey);
        return openAiStreamClient;
    }

    public static OpenAiStreamClient createOpenAiStreamClient(String apiHost, String apiKey) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(600, TimeUnit.SECONDS)
            .readTimeout(600, TimeUnit.SECONDS)
            .build();
        return OpenAiStreamClient.builder()
            .apiHost(apiHost)
            .apiKey(Collections.singletonList(apiKey))
            .keyStrategy(new KeyRandomStrategy())
            .okHttpClient(okHttpClient)
            .build();
    }

    /**
     * 创建适配阿里云百炼（DashScope）接口的客户端
     *
     * @param apiKey 百炼 API Key
     * @return OpenAiStreamClient 实例
     */
    public static OpenAiStreamClient createDashScopeClient(String apiHost, String apiKey) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(chain -> {
                    return chain.proceed(chain.request().newBuilder()
                            .header("Authorization", "Bearer " + apiKey)
                            .header("Content-Type", "application/json")
                            .build());
                })
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(600, TimeUnit.SECONDS)
                .readTimeout(600, TimeUnit.SECONDS)
                .build();

        return OpenAiStreamClient.builder()
                .apiHost(apiHost)
                .apiKey(Collections.singletonList(apiKey))
                .keyStrategy(new KeyRandomStrategy())
                .okHttpClient(okHttpClient)
                .build();
    }


}
